package no.cicero.testframework.execution;

import no.cicero.testframework.config.Config;
import no.cicero.testframework.execution.exceptions.TestFailedRuntimeException;
import no.cicero.testframework.model.testcase.TestCase;
import no.cicero.testframework.model.usecase.UseCase;
import no.cicero.testframework.xml.testcase.TestCaseImporter;
import no.cicero.testframework.xml.usecase.UseCaseImporter;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.IOException;

/**
 * Author: Sergiy Doroshenko
 * Date: Jun 15, 2010
 * Time: 3:32:38 PM
 */
public class UseCasesRunnerWithOutReport implements Runnable {
    public static final String OUTPUT_DEFAULT_FOLDER = "report";

    private final Config config;
    	private final SAXParser parser;

    public UseCasesRunnerWithOutReport(Config cfg) throws ParserConfigurationException,SAXException, IOException {
        config = cfg;
        parser = SAXParserFactory.newInstance().newSAXParser();
    }

    public void run() {
        try {
            runUseCases();
        } catch (Exception ex) {
            throw new TestFailedRuntimeException(ex);
        }
    }

    private void runUseCases() throws IOException {
        for (String useCaseFile : config.getUseCaseNames()) {
            try {
                executeUseCase(useCaseFile);
                //use case succeed
            } catch (Exception ex) {
                throw new TestFailedRuntimeException(ex);
            }
        }
    }

    private void executeUseCase(String useCaseFile) throws IOException, SAXException {
        UseCase useCase = new UseCaseImporter(parser).doImport(new File(config.getUseCaseLocation(), useCaseFile));


        for (String testCaseName : useCase.getTestCases()) {
            if (!config.matchesTestCase(testCaseName))
                continue;
            TestCase testCase = loadTestCase(testCaseName, useCase);
            try {
                executeTestCase(testCase);
                //test case succeed
            } catch (Exception ex) {
                //test case failed
                 throw new TestFailedRuntimeException(testCaseName + " are failed " ,ex);
            }
        }
    }

    private TestCase loadTestCase(String testCaseName, UseCase useCase) throws IOException, SAXException {
        TestCase testCase = new TestCaseImporter(parser).doImport(
                new File(new File(config.getTestCaseLocation(), useCase.getTestCaseLocation()), testCaseName)
        );

        return testCase;
    }

    private void executeTestCase(TestCase testCase) throws Exception {
        TestCaseRunner runner = new TestCaseRunnerWithOutReport(testCase, config);
        runner.run();
    }

}
